<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<title>vkposter.com</title>
	<meta name="keywords" content="vkposter.com" />
	<meta name="description" content="vkposter.com" />
	<link rel="stylesheet" href="/style/bootstrap.css" type="text/css" media="screen, projection" />
	<link rel="stylesheet" href="/style/style.css" type="text/css" media="screen, projection" />
	<link rel="stylesheet" href="/style/jcrop.css" type="text/css" media="screen, projection" />
	<link rel="stylesheet" href="/style/jquery-ui.css" type="text/css" media="screen, projection" />
	<script src="/javascript/jquery.js"></script>
	<script src="/javascript/jquery.ui.js"></script>
	<script src="/javascript/bootstrap.min.js"></script>
	<script src="/javascript/plugin.jcrop.js"></script>
</head>

<body>

<div id="wrapper">

    <div id="header">
        <div class="head_center">
            <ul >
                <li>
                	<a href="/">Главная</a>
                </li>
            </ul>
        </div>

        <div class="head_right">
            <ul>
                <li >Привет, <?php echo $this->user->getName(); ?></li>
                <li><a href="/auth/clear.token">Стереть токен</a></li>
                <li><a href="/auth/logout" title="">Выйти</a></li>
            </ul>
        </div>	
    </div><!-- #header-->

	<div id="middle">
		
		<div id="container">
			<div id="content">
				<?php echo $this->layout()->content; ?>
				<div class="help_block">
					<h1><a href='#' onclick="logUpdate(); return false;">Показать логи</a></h1>
					<div id="log_list" style="display: none;">
						
					</div>
				</div>
			</div><!-- #content-->
		</div><!-- #container-->

		<div class="sidebar" id="sideLeft">
				<div class="head">Лента событий</div>
				<div class="side_body"><ul class="eventList" id="event_list">
					<?php foreach(array() as $act): ?>
						<li>
							<p><?php echo $act['text']; ?></p>
							<span><?php echo $act['created_at']; ?></span>
						</li>
					<?php endforeach; ?>
				</ul></div>
		</div><!-- .sidebar#sideLeft -->

		<div class="sidebar" id="sideRight">
                    <div class="head">Действия</div>
                    <div class="side_body">
                            Группа: <select id="groups_list" style="width: 200px;">
                                    <?php 
                                            foreach($this->groups as $group): 
                                            $watermark = '/images/groups/'.$group->vk_id.'/watermark.png';
                                            if(!is_file($_SERVER['DOCUMENT_ROOT'] . $watermark)){
                                                    $watermark = 'none';
                                            }
                                            $to_url = 'http://vk.com/' . $group->url;
                                            $edit_url = '/group/edit?id=' . $group->vk_id;
                                    ?>
                                    <option 
                                        data-watermark="<? echo $watermark ?>" 
                                        data-href-to="<? echo $to_url ?>" 
                                        data-href-edit="<?php echo $edit_url ?>" 
                                        id="<?php echo $group->vk_id ?>" 
                                        <?php echo (isset($_SESSION['current_group']) && $_SESSION['current_group'] == $group->vk_id) ? 'selected' : '';?>
                                    >
                                        <?php echo $group->name; ?>
                                    </option>
                                    <?php endforeach; ?>
                            </select>
                            <a id="group_link" href="" target="_blank"><i class="icon-share-alt" style="cursor: pointer;"></i></a>
                            <a id="group_edit" href=""><i class="icon-cog" style="cursor: pointer;"></i></a>
                            <?php if(null != $this->post || !empty($this->post)): ?>
                            <div>
                                    <a id="copy_title" href="#">Скопировать из описания</a>
                                    <textarea id="description" style="width: 95%; height: 80px;" placeholder="Введите описание..."></textarea>
                            </div>
                            <div style="text-align: center">
                                    <button id="post_add" data-loading-text="Обработка..." class="btn btn-success btn-large">Запостить</button>					
                                    <button id="post_del" data-loading-text="Обработка..." class="btn btn-danger btn-large">Удалить</button>
                                    <button id="post_add_turn" data-loading-text="Обработка..." class="btn btn-inverse btn-large" style="margin-top: 5px;">Добавить в очередь</button>
                            </div>
                            <?php endif; ?>
                    </div>
                    <br/>
                    <div class="head">Очередь</div>
                    <div class="side_body" id="turn_container">
                        
                    </div>
                    <br/>
		</div><!-- .sidebar#sideRight -->

	</div><!-- #middle-->

</div><!-- #wrapper -->

<div id="footer">
&copy; VkPoster 2012
</div><!-- #footer -->
<div class="modal hide fade" id="myModal">
  <div class="modal-header">
    <button class="close" data-dismiss="modal">×</button>
    <h3></h3>
  </div>
  <div class="modal-body">
  </div>
</div>
<div class="modal hide" id="piModal">
  <div class="modal-header">
    <button class="close" data-dismiss="modal">×</button>
    <h3>Обрежте картинку</h3>
  </div>
  <div class="modal-body">
  	<div class="wrap_img"></div>
  </div>
  <div class="modal-footer">
  	<div class="tool_bar">
  		<div class="edit">
  			Watermark: 
			<select class="span2" id="watermark">
				<option id="northwest">Слева сверху</option>
				<option id="southwest">Слева снизу</option>
				<option id="northeast">Справа сверху</option>
				<option id="southeast" selected>Справа снизу</option>
				<option id="center">По центру</option>
				<option id="none">Без вотермарка</option>
			</select>
  		</div>
  		<div class="message">
  			<div id="success">
  				
  			</div>
  		</div>
		<div class="actions">	
    		<button class="btn btn-primary" id="save" data-loading-text="Обработка...">Сохранить</button>
    		<button class="btn" data-dismiss="modal" id="cancel">Отмена</button>
    	</div>
    </div>
  </div>
</div>

<div class="modal hide fade" id="preloader">
  <div class="modal-header">
    <h3>Обработка запроса</h3>
  </div>
  <div class="modal-body">
	<img src="/images/loader_32.gif" style="float: left" />
	<span style="display: inline-block; margin: 10px; font-size: 16px;">Пожалуйста дождитесь обработки данных!</span>
  </div>
</div>

<div class="modal hide fade" id="captcha">
  <div class="modal-body" style="text-align: center">
	<p><img src=""/></p>
	<input type="hidden" id="captcha_sid" value=""/>
	<input type="hidden" id="owner_id" value=""/>
	<input type="hidden" id="message" value=""/>
	<input type="hidden" id="attachments" value=""/>
	
	<p><input type="text" id="captcha_key" value=""/></p>
	<p><button class="btn" id="captcha_send">Отправить</button></p>
  </div>
</div>
<script>
var post_add = $('#post_add');
var post_del = $('#post_del');
var post_add_turn = $('#post_add_turn');
var imgCropPosition = 0;
var pi = $('#post_img');
var info_block = $('#info-block');
var pi_modal = $('#piModal');
var preloader_modal = $('#preloader');
var log_list = $('#log_list');
var captcha = $('#captcha');
var imgSize = {
	height: 0, width: 0, newHeight: 0, newWidth: 0
};
var turn_container = $('#turn_container');
var turns_list = $('#turns_list');
function setGroupLinks(){
	var edit_link = $("option:selected", '#groups_list').attr('data-href-edit');
	var to_link = $("option:selected", '#groups_list').attr('data-href-to');
	var w = $("option:selected", '#groups_list').attr('data-watermark');
	if(w == "none"){
		$('#watermark').parent().hide();
	}else{
		$('#watermark').parent().show();
	}
	$('#group_link').attr('href', to_link);
	$('#group_edit').attr('href', edit_link);
        turnsLoad($("option:selected", '#groups_list').attr('id'));
}
setGroupLinks();
$('#groups_list').change(function(){	
	setGroupLinks();
});
$('#copy_title').click(function(){
	var str = $('.title').text();
	str = str.charAt(0).toUpperCase() + str.substr(1);
	$('#description').html( str );
	return false;
});
$('#captcha_send').click(function(){
	var data = {
		pid: $('#pid').val(),
		captcha_sid: $('#captcha_sid').val(),
		owner_id: $('#owner_id').val(),
		message: $('#message').val(),
		attachments: $('#attachments').val(),
		captcha_key: $('#captcha_key').val()
	}
	$.ajax({
		url: '/default/index/captchapost',
		type: 'POST',
		dataType: 'json',
		data: data,
		success: function(response){
			if(response.status === 'OK'){
				console.log(response);
				return;
			}
			alert(response.body);
		}
	});	
});
pi.load(function (){
	var h, w, css;
	h = imgSize.height = pi.height();
	w = imgSize.width = pi.width();
	if(imgSize.width > 550){
		pi.css('width', 550);
		h = imgSize.newHeight = pi.height();
		w = imgSize.newWidth = pi.width();
	}
});
$('#post_img, #prev_img').click(function(){
	var setSelect;
	pi_modal
		.css('width',800)
		.css('position', 'absolute')
		.find('.modal-body').css('maxHeight', 'none')
		//.css('height', 600)
			.find('.wrap_img')
			.html('<img style="margin:0px; padding: 0px;" src="' + pi.attr('data-simple') + '" id="piCrop"/>')
		.parent().parent()
		.css('top', '10px')
		.css('left', '50%')
		.css('margin', 'none')
		.css('margin-left', -400)
		.css('margin-top', '50px')
		.modal({backdrop: true}).modal('show');
	$('#piCrop').load(function(){
            var crop_w = $('#piCrop').width(), 
                crop_h = $('#piCrop').height(),
                button_crop = 0,
                uriParts = window.location.pathname.split('/'),
                pageName = uriParts[uriParts.length-1];
            if(pageName == 'pikabu' || pageName == ''){
                    button_crop = 13;
            }else if(pageName == 'koto'){
                    button_crop = 20;
            }
            $('#piCrop').Jcrop({
                    onSelect: imgAddWatermark,
                    onChange: imgCrop,
                    setSelect: [0, 0, crop_w, crop_h-button_crop]
            });
	});
});
$('#save').click(function(){
	$(this).button('loading');
	$('#cancel', pi_modal).attr('disabled', 'disabled');
	var gravity = $('option:selected', '#watermark').attr('id');
	if($("option:selected", '#groups_list').attr('data-watermark') == 'none'){
		gravity = 'none';
	}
	var data = {
		'crop': imgCropPosition,
		'img': pi.attr('data-simple'),
		'gravity': gravity,
		'pid': $('#pid').val(),
		'gid': $('option:selected', '#groups_list').attr('id')
	};
	preloader_show();
	$.ajax({
		url: '/default/posting/crop.image',
		type: 'POST',
		dataType: 'json',
		data: data,
		success: function(response){
			if(response.status === 'OK'){
				preloader_close();
				$('#cancel', pi_modal).removeAttr('disabled');
				$('#save').button('reset');
				pi.attr('src', response.body.img_src+"?_t="+new Date().getTime());
				pi_modal.modal('hide');
				return;
			}
			alert(response.body);
		}
	});	
	return false;
});
function imgCrop(c){
	imgCropPosition = c;
}
function imgAddWatermark(c){
	imgCropPosition = c;
	var w = $("option:selected", '#groups_list').attr('data-watermark');
	if(w != "none"){
		var tracker = $('.jcrop-tracker');
		$(tracker[0]).html('<img id="im_watermark" src="' + w + '" style="position: absolute;" />');
		watermarkPreview();
	}
}
function preloader_show(){
	preloader_modal.modal({keyboard: false, backdrop: false}).css('zIndex', 2000);
	$('body').append('<div class="modal-backdrop" style="z-index: 1999;"></div>');
	preloader_modal.modal('show');
}
function preloader_close(){
	preloader_modal.modal('hide');
	var backdrop = $('.modal-backdrop', 'body');
	$(backdrop[1]).remove();
}
function watermarkPreview(){
	var current = $('option:selected', '#watermark').attr('id');
	var wid = $('#im_watermark');
	if(current != 'none'){
		wid.show();
		switch(current){
			case 'northwest':
				wid.
					css('left',0).
					css('top',0).
					css('bottom','').
					css('right','').
					css('marginLeft', 0).
					css('marginTop', 0);
			break;
			case 'southwest':
				wid.
					css('left',0).
					css('bottom',0).
					css('top', '').
					css('right', '').
					css('marginLeft', 0).
					css('marginTop', 0);
			break;
			case 'northeast':
				wid.
				css('right', 0).
				css('top', 0).
				css('left', '').
				css('bottom', '').
				css('marginLeft', 0).
				css('marginTop', 0);
			break;
			case 'southeast':
				wid.
				css('right', 0).
				css('bottom', 0).
				css('left', '').
				css('top', '').
				css('marginLeft', 0).
				css('marginTop', 0);
			break;
			default:
				wid.css('left', '50%').
					css('top', '50%').
					css('marginLeft', -(wid.width() / 2)).
					css('marginTop', -(wid.height() / 2));
		}
	}else{
		wid.hide();
	}
}
$('#watermark').change(function(){
	watermarkPreview();
});
post_add.click(function(){
    post_add.button('loading');
    post_del.attr('disabled', 'disabled');
    post_add_turn.attr('disabled', 'disabled');
    var query = '/posting/post?'+
        'img='+pi.attr('src')+'&'+
        'text='+$('#description').val()+'&'+
        'pid='+$('#pid').val()+'&'+
        'gid='+$('option:selected', '#groups_list').attr('id');
    window.location = query;
    return false;
});
post_del.click(function(){
    post_del.button('loading');
    post_add.attr('disabled', 'disabled');
    post_add_turn.attr('disabled', 'disabled');
    var query = '/posting/del?'+
        'pid='+$('#pid').val()+'&'+
        'gid='+$('option:selected', '#groups_list').attr('id');
    window.location = query;
    return false;
});
post_add_turn.click(function(){
    post_add_turn.button('loading');
    post_add.attr('disabled', 'disabled');
    post_del.attr('disabled', 'disabled');
    var query = '/posting/add.turn?'+
        'pid='+$('#pid').val()+'&'+
        'tid='+$('#tid').val()+'&'+
        'img='+pi.attr('src')+'&'+
        'text='+$('#description').val();
    window.location = query;
    return false;
});
var eL = $('#event_list, #turn_list');
var window = $('#myModal');
$('li a', eL).click(function(){
	$('#myModal')
		.css('width','600')
		.css('height','500')
		.find('.modal-header')
		.find('h3').html($(this).parent().text()).parent().parent()
		.find('.modal-body').html('<img src="/images/loader_32.gif" style="float: left" /><span style="display: inline-block; margin: 10px; font-size: 16px;">Загружаю пост, ждите!</span>').parent().modal('show');
		$.get($(this).attr('href'), {}, function(r){
			$('#myModal').find('.modal-body').html(r);
		});
	return false;
});

function logUpdate(){
	log_list.html('<center><img src="/images/loader_32.gif"/></center>').fadeIn();
	$.ajax({
		url: '/default/index/log',
		type: 'POST',
		dataType: 'json',
		data: {},
		success: function(response){
			if(response.status === 'OK'){
				var html = '';
				$.each(response.body, function(log){
					html += '<ul>';
					html += '<li class="header">'+this.action+' <span>'+this.timestamp+'</span></li>';
					html += '<li><pre>'+this.message+'</pre></li>';
					html += '<li>User: '+this.user_name+'</li>';
					html += '</ul>';
				});
				log_list.html(html);
				return;
			}
			alert(response.body);
		}
	});
	return false;
}

$('#log_list ul li').live('click', function(){
	if($.browser.msie){
		var range = document.body.createTextRange();
	    var tab=this;
	    range.moveToElementText(tab);
	    range.select();							
	}else{
		var selection = window.getSelection();
	    var range = document.createRange();
	    var tab = this;
	    range.selectNodeContents(tab);
	    selection.addRange(range);
	}
});

// загрузка списока очередей
function turnsLoad(group_id) {
    turn_container.html('<img src="/images/loader_32.gif"/>');
    $.ajax({
        url: '/turn/get.turns',
        type: 'POST',
        data: {group: group_id},
        dataType: 'html',
        success: function(response) {
            /*turns_list.html('');
            var thtml = '<ul id="turn_list">';
            $.each(response.body, function(position, turn){
                // обновляем кнопку очередей
                turns_list.append('<li><a href="/posting/add.turn?id=' + this.turn.id + '&post_id=' + $('#pid').val() + '&img=' + pi.attr('src') + '&text=' + $('#description').val() + '">' + this.turn.name + '</a></li>');
                
                // обновляем список очередей
                thtml += '<li><div class="header">' + this.turn.name + '</div>';
                if(this.posts.length <= 0){
                    thtml += '<ul><li>Постов еще нет</li></ul>';
                }else{
                    thtml += '<ul>';
                    $.each(this.posts, function(){
                        thtml += '<li>Пост - <a href="/posting/get?id=' + this.id + '">' + this.post_id + '</a>';
                        thtml += '<p style="float: right;">' + this.post_date + '</p></li>';
                    });
                    thtml += '</ul>';
                }
                thtml += '</li>';
            });
            thtml += '</ul>';*/
            turn_container.html(response);
        },
        error: function() {
            turn_container.html('Ошибка при обработке запроса');
        }
    });
}
</script>
</body>
</html>
